package com.example.k12.utlis

import android.content.Context
import android.os.RemoteException
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.tencent.wxpayface.IWxPayfaceCallback
import com.tencent.wxpayface.WxPayFace
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit


// 创建一个Worker类
class FaceDataUpdateWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
    override fun doWork(): Result {
        Log.d(TAG, "开始执行人脸数据更新任务")
        // 使用CountDownLatch等待异步回调完成
        val latch = CountDownLatch(1)
        val updateSuccess = booleanArrayOf(false)

        try {
            // 执行人脸数据更新
            WxPayFace.getInstance()
                .manualUpdateFaceDatas(WxPayUtils.params, object : IWxPayfaceCallback() {
                    @Throws(RemoteException::class)
                    override fun response(info: MutableMap<*, *>?) {
                        try {
                            if (info == null) {
                                Log.e(TAG, "更新人脸信息返回为空")
                            } else {
                                val code = info.get("return_code") as String?
                                val msg = info.get("return_msg") as String?
                                if (code != null && code == "SUCCESS") {
                                    updateSuccess[0] = true
                                    Log.d(TAG, "人脸信息更新成功")
                                } else {
                                    Log.e(TAG, "更新人脸信息调用失败, return_msg:" + msg)
                                }
                            }
                        } finally {
                            latch.countDown()
                        }
                    }
                })


            // 等待异步回调完成（设置超时时间避免无限等待）
            latch.await(30, TimeUnit.SECONDS)


            // 根据执行结果返回相应的Result
            return if (updateSuccess[0]) Result.success() else Result.retry()
        } catch (e: Exception) {
            Log.e(TAG, "执行人脸数据更新时发生异常", e)
            return Result.retry()
        }
    }

    companion object {
        private const val TAG = "FaceDataUpdateWorker"
    }
}